/*
Copyright (C) 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

function Team() {
  this.id = null;
  this.name = null;
  this.winCount = null;
  this.lossCount = null;
  this.tieCount = null;
  this.seed = null;
}

Team.prototype.getIcon = function() {
  return 'images/' + this.name.substr(0, 3) + '_small.gif';
};

Team.parseTeams = function(responseText) {
  var teams = {};

  var lines = responseText.split('\n');

  for (var i = 0; i < lines.length; ++i) {
    var teamElementArray = lines[i].split(';');
    if (teamElementArray.length > 1) {
      var team = new Team();
      team.id = teamElementArray[0];
      team.name = teamElementArray[1];
      teams[team.id] = team;
    }
  }

  return teams;
};


function Match() {
  this.date = null;
  this.status = null;
  this.awayId = null;
  this.homeId = null;
  this.awayTeam = null;
  this.homeTeam = null;
  this.startTime = null;
  this.awayScore = null;
  this.homeScore = null;
  this.half = null;
  this.minute = null;
  this.newsLink = null;
  this.localStartTime = null;
  this.actions = [];
}

Match.STATUS_UPCOMING = 0;
Match.STATUS_LIVE = 1;
Match.STATUS_FINAL = 2;

Match.prototype.isUpcoming = function() {
  return this.status == Match.STATUS_UPCOMING;
};

Match.prototype.isLive = function() {
  return this.status == Match.STATUS_LIVE;
};

Match.prototype.isFinal = function() {
  return this.status == Match.STATUS_FINAL;
};

// Expects local time date.
Match.prototype.isFallsOnDate = function(date) {
  return isDateEqual(this.localStartTime, date);
};

Match.prototype.formatLocalStartTime = function() {
  if (!this.localStartTime) {
    return '';
  }

  var hours = this.localStartTime.getHours();
  var minutes = this.localStartTime.getMinutes();

  hours += '';
  if (hours.length < 2) {
    hours = '0' + hours;
  }

  minutes += '';
  if (minutes.length < 2) {
    minutes = '0' + minutes;
  }

  return hours + ':' + minutes;
};

Match.prototype.getTitle = function() {
  return this.getAwayName() + ' ' + strings.VS + ' ' + this.getHomeName();
};

Match.prototype.getTime = function() {
  if (this.isUpcoming()) {
    return this.formatLocalStartTime();
  } else if (this.isFinal()) {
    return strings.FINAL;
  } else {
    return this.minute;
  }
};

Match.NEWS_URL = 'http://www.news.google.com/news?q=euro+2008+soccer';

Match.prototype.getNewsLink = function() {
  var newsUrl = Match.NEWS_URL + '+' +
                encodeURIComponent(this.getAwayName()) + '+' +
                encodeURIComponent(this.getHomeName());

  return newsUrl;
};

Match.prototype.getActions = function() {
  this.actions.sort(Action.sorter);

  return this.actions;
};

Match.prototype.getHomeName = function() {
  return this.homeTeam ? this.homeTeam.name : '';
};

Match.prototype.getAwayName = function() {
  return this.awayTeam ? this.awayTeam.name : '';
};

Match.prototype.getHomeScore = function() {
  return this.homeScore !== null ? this.homeScore : '';
};

Match.prototype.getAwayScore = function() {
  return this.awayScore !== null ? this.awayScore : '';
};

Match.prototype.getHomeIcon = function() {
  return this.homeTeam ? this.homeTeam.getIcon() : '';
};

Match.prototype.getAwayIcon = function() {
  return this.awayTeam ? this.awayTeam.getIcon() : '';
};

Match.parseSchedule = function(responseText, teams) {
  var schedule = [];
  var dateArray = responseText.split('+');

  for (var i = 1; i < dateArray.length; ++i) {
    var gameArray = dateArray[i].split('\n');
    var date = gameArray[0];
    for (var j = 1; j < gameArray.length; ++j) {
      var gameElementArray = gameArray[j].split(';');

      if (gameElementArray.length > 1) {
        var match = new Match();
        match.date = date;
        match.status = Number(gameElementArray[0]);
        match.awayId = gameElementArray[1];
        match.homeId = gameElementArray[2];

        match.awayTeam = teams[match.awayId];
        match.homeTeam = teams[match.homeId];

        if (match.status === Match.STATUS_UPCOMING) {
          match.startTime = gameElementArray[3];
        } else {
          match.startTime = gameElementArray[5];
          match.awayScore = gameElementArray[3];
          match.homeScore = gameElementArray[4];
          if (match.status == Match.STATUS_LIVE) {
            match.half = gameElementArray[6];
            match.minute = gameElementArray[7];
            match.actions = Action.parseActions(gameElementArray, 8, teams);
          } else {
            match.newsLink = gameElementArray[6];
            match.actions = Action.parseActions(gameElementArray, 7, teams);
          }
        }

        // Build a UTC start time.
        var localStartTime = new Date();
        localStartTime.setUTCFullYear(match.date.substr(0, 4));
        localStartTime.setUTCMonth(match.date.substr(4, 2) - 1);
        localStartTime.setUTCDate(match.date.substr(6, 2));
        localStartTime.setUTCHours(match.startTime.substr(0, 2));
        localStartTime.setUTCMinutes(match.startTime.substr(2, 2));
        localStartTime.setUTCSeconds(0);

        // CET is UTC+1
        var offsetMs = +1 * 60 * 60 * 1000;
        localStartTime.setTime(localStartTime.getTime() - offsetMs);

        match.localStartTime = localStartTime;

        schedule.push(match);
      }
    }
  }

  return schedule;
};

Match.sorter = function(a, b) {
  return a.localStartTime - b.localStartTime;
};


function Action() {
  this.type = null;
  this.teamId = null;
  this.team = null;
  this.half = null;
  this.minute = null;
  this.playerName = null;
  this.playerName2 = null;
}

Action.GOAL = 'g';
Action.PENALTY_GOAL = 'p';
Action.SUBSTITUTION = 's';
Action.RED_CARD = 'r';
Action.YELLOW_CARD = 'y';

Action.GOAL_ICON = 'goal.gif';
Action.RED_CARD_ICON = 'red.gif';
Action.YELLOW_CARD_ICON = 'yellow.gif';

Action.prototype.getIcon = function() {
  if (this.type == Action.GOAL ||
      this.type == Action.PENALTY_GOAL) {
    return Action.GOAL_ICON;
  } else if (this.type == Action.RED_CARD) {
    return Action.RED_CARD_ICON;
  } else if (this.type == Action.YELLOW_CARD) {
    return Action.YELLOW_CARD_ICON;
  }

  return '';
};

Action.prototype.getTeamIcon = function() {
  return this.team ? this.team.getIcon() : '';
};

Action.parseActions = function(gameElementArray, start, teams) {
  var actions = [];

  for (var i = start; i < gameElementArray.length; ++i) {
    var actionArray = gameElementArray[i].split('.');

    if (actionArray.length > 1) {
      var action = new Action();
      action.type = actionArray[0];
      action.teamId = actionArray[1];
      action.team = teams[action.teamId];
      action.half = actionArray[2];
      action.minute = actionArray[3];
      action.playerName = actionArray[4];
      if (action.type == Action.SUBSTITUTION) {
        action.playerName2 = actionArray[5];
      }

      if (action.type != Action.SUBSTITUTION) {
        actions.push(action);
      }
    }
  }

  return actions;
};

Action.sorter = function(a, b) {
  return b.minute - a.minute;
};
